<template>
  <div class="tinymce-editor">
    <editor
      v-if="!reloading"
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick">
    </editor>
    <a-upload
      style="display: none"
      :customRequest="upload"
      :beforeUpload="handleBeforeUpload"
    >
      <a-button ref="imageUpload"> <a-icon type="upload" /> Click to Upload </a-button>
    </a-upload>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/modern/theme'
import Editor from '@tinymce/tinymce-vue'

import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/fullscreen'

import { apiUploadFile, VIEW_FILE_URL } from '@/api/file'

export default {
  components: {
    Editor
  },
  props: {
    value: {
      type: String,
      required: false
    },
    triggerChange: {
      type: Boolean,
      default: false,
      required: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    plugins: {
      type: [String, Array],
      default: 'lists image link media table textcolor wordcount contextmenu fullscreen powerpaste preview'
    },
    toolbar: {
      type: [String, Array],
      default: 'undo redo |  formatselect | fontselect fontsizeselect forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists link unlink imageUpload media table | removeformat | fullscreen preview',
      branding: false
    }
  },
  data () {
    return {
      // 初始化配置
      init: {
        language_url: '/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/tinymce/skins/lightgray',
        height: 300,
        plugins: this.plugins,
        toolbar: this.toolbar,
        branding: false, // 去水印
        menubar: false, // 隐藏最上方menu
        toolbar_drawer: false,
        paste_data_images: true, // 允许粘贴图像
        setup: (editor) => {
          console.log(editor)
          /**
           * 下面方法是为tinymce添加自定义插入图片按钮
           * 借助ant的Upload组件,将图片先上传到存储云上，再将图片的存储地址放入编辑器内容
           */
          editor.addButton('imageUpload', {
            tooltip: '插入图片',
            icon: 'image',
            onclick: () => {
              const upload = this.$refs.imageUpload
              upload.$el.click()
            }
          })
        },
        images_upload_handler: (blobInfo, success) => {
          const formData = new FormData()
          formData.append('file', blobInfo.blob(), blobInfo.filename())
          formData.append('biz', 'jeditor')
          formData.append('jeditor', '1')
          // uploadAction(window._CONFIG['domianURL'] + '/sys/common/upload', formData).then((res) => {
          //   if (res.success) {
          //     if (res.message == 'local') {
          //       const img = 'data:image/jpeg;base64,' + blobInfo.base64()
          //       success(img)
          //     } else {
          //       const img = getFileAccessHttpUrl(res.message)
          //       success(img)
          //     }
          //   }
          // })
        }
      },
      myValue: this.value,
      reloading: false
    }
  },
  mounted () {
    this.initATabsChangeAutoReload()
  },
  methods: {

    reload () {
      this.reloading = true
      this.$nextTick(() => this.reloading = false)
    },

    onClick (e) {
      this.$emit('onClick', e, tinymce)
    },
    // 可以添加一些自己的自定义事件，如清空内容
    clear () {
      this.myValue = ''
    },

    /**
     * 自动判断父级是否是 <a-tabs/> 组件，然后添加事件监听，自动触发reload()
     *
     * 由于 tabs 组件切换会导致 tinymce 无法输入，
     * 只有重新加载才能使用（无论是vue版的还是jQuery版tinymce都有这个通病）
     */
    initATabsChangeAutoReload () {
      // 获取父级
      const tabs = this.getVmParentByName(this, 'ATabs')
      const tabPane = this.getVmParentByName(this, 'ATabPane')
      if (tabs && tabPane) {
        // 用户自定义的 key
        const currentKey = tabPane.$vnode.key
        // 添加事件监听
        tabs.$on('change', (key) => {
          // 切换到自己时执行reload
          if (currentKey === key) {
            this.reload()
          }
        })
      } else {
        const tabLayout = this.getVmParentByName(this, 'TabsView')
        tabLayout.excuteCallback(() => {
          this.reload()
        })
      }
    },
    /**
     * 根据组件名获取父级
     * @param vm
     * @param name
     * @returns {Vue | null|null|Vue}
     */
    getVmParentByName (vm, name) {
      const parent = vm.$parent
      if (parent && parent.$options) {
        if (parent.$options.name === name) {
          return parent
        } else {
          const res = this.getVmParentByName(parent, name)
          if (res) {
            return res
          }
        }
      }
      return null
    },

    // 插入图片至编辑器
    upload (e) {
      const formData = new FormData()
      formData.append('multipartFile', e.file)
      apiUploadFile(formData).then(res => {
        tinymce.execCommand('mceInsertContent', false, `<img src=${VIEW_FILE_URL + res.data.id}>`)
        e.onSuccess()
      }).catch(err => {
        e.onError(err, err.message)
      })
    },
    handleBeforeUpload (file, fileList) {
      console.log(file, fileList)
    }

  },
  watch: {
    value (newValue) {
      this.myValue = (newValue == null ? '' : newValue)
    },
    myValue (newValue) {
      if (this.triggerChange) {
        this.$emit('change', newValue)
      } else {
        this.$emit('input', newValue)
      }
    }
  }
}

</script>
<style scoped>
</style>
